using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.Runtime.CompilerServices;

namespace Weight.Base
{
    public  class XMLHelper
    {
        /// <summary>
        /// 获取指定路径的xmlNode
        /// </summary>
        /// <param name="path">配置文件路径</param>
        /// <param name="node">根节点名称</param>
        /// <returns>返回根节点</returns>
        public static XmlNode getXmlNode(string path, string node)
        {
            if (!File.Exists(path)) return null;
            XmlDocument doc = new XmlDocument();
            doc.Load(path);
            return doc.SelectSingleNode(node);
        }

        /// <summary>
        /// 获取xml文件的根节点
        /// </summary>
        /// <param name="path">配置文件路径</param>
        /// <returns></returns>
        public static XmlNode getXmlNode(string path)
        {
            if (!File.Exists(path)) return null;
            XmlDocument doc = new XmlDocument();
            doc.Load(path);
            return doc.DocumentElement;
        }

        /// <summary>
        /// 获取新XML文档的表头和定义
        /// </summary>
        /// <returns>返回新的XML配置文件头</returns>
        public static XmlDocument getXmlDocHeader()
        {
            XmlDocument doc = new XmlDocument();
            XmlDeclaration dcl = doc.CreateXmlDeclaration("1.0", "utf-8", null);
            doc.AppendChild(dcl);
            return doc;
        }

        /// <summary>
        /// 生成配置文件
        /// </summary>
        /// <param name="path">文件保存路径</param>
        /// <param name="data">数据集合</param>
        /// <param name="rootName">跟目录名称</param>
        /// <returns></returns>
        public   ResponseResult MakeXml(string path,List<string> data,string rootName)
        {
            var result = ResponseResult.Default();
            try
            {
                if (string.IsNullOrEmpty(rootName)) rootName = "root";
                XmlDocument doc = getXmlDocHeader();
                XmlElement root = doc.CreateElement(rootName);
                doc.AppendChild(root);
                XmlElement ele = null;
                foreach (string item in data)
                {
                    ele = doc.CreateElement(item);
                    root.AppendChild(ele);
                }

                doc.Save(path);
                result = ResponseResult.Success("操作成功");
            }
            catch(Exception ex)
            {
                result = ResponseResult.Error("操作异常:"+ex.Message+ex.StackTrace);
            }

            return result;
        }

        /// <summary>
        ///获取xml文件
        /// </summary>
        /// <param name="path">路径</param>
        /// <param name="rootName">根节点名称</param>
        /// <returns></returns>
        public ResponseResult<List<string>> GetXmlConfig(string path,string rootName)
        {
            var result = ResponseResult<List<string>>.Default();
            try
            {
                if (!File.Exists(path))
                {
                    result = ResponseResult<List<string>>.Error("操作失败,文件不存在!");
                }
                else
                {
                    XmlNode node = getXmlNode(path, rootName);
                    List<string> list = new List<string>();
                    if (node != null)
                    {
                        foreach (XmlNode item in node.ChildNodes)
                        {
                            list.Add(item.Name);
                        }
                    }

                    result = ResponseResult<List<string>>.Success(list);
                }
            }
            catch(Exception ex)
            {
                result = ResponseResult<List<string>>.Error("操作异常:"+ex.Message+ex.StackTrace);
            }
            return result;
        }

        /// <summary>
        /// 对象序列化为xml字符串
        /// </summary>
        /// <typeparam name="T">类型</typeparam>
        /// <param name="obj">要实例的对象</param>
        /// <returns></returns>
        public static string Serialize<T>(T obj)
        {
            try
            {
                using (StringWriter sw = new StringWriter())
                {
                    XmlSerializer xmls = new XmlSerializer(obj.GetType());
                    xmls.Serialize(sw, obj);
                    sw.Close();
                    return sw.ToString();
                }
            }
            catch(Exception ex)
            {
                LogHelper.WriteLog("序列化对象到xml", ex);
                return null;
            }
        }

        /// <summary>
        /// 反序列化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="xml"></param>
        /// <returns></returns>

       public static T DESerialize<T>(string xml) where T:class
       {
            try
            {
                using (StringReader reader = new StringReader(xml))
                {
                    XmlSerializer xmls = new XmlSerializer(typeof(T));
                    return xmls.Deserialize(reader) as T;
                }
            }
            catch(Exception ex)
            {
                LogHelper.WriteLog("xml 反序列化", ex);
                return null;
            }
       }
    }
}


